package com.turtle.api;

import com.turtle.constant.EsConst;
import com.turtle.dto.BlogInfoDto;
import com.turtle.entity.sql.EsBlog;
import com.turtle.feign.BlogFeignClientService;
import com.turtle.feign.EsFeignApi;
import com.turtle.service.EsSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.time.ZonedDateTime;

/**
 * @author lijiayu
 * @date 2020/7/28
 * @description
 */
@Service
@ResponseBody
@Slf4j
public class EsApi implements EsFeignApi {

    @Autowired
    private EsSearchService esSearchService;
    @Autowired
    private BlogFeignClientService blogClientService;

    @Override
    public void addElasticIndexById(Long id) {
        try {
            BlogInfoDto blogInfo = blogClientService.getBlogInfoById(id);
            EsBlog esBlog = EsBlog.builder()
                    .id(blogInfo.getId())
                    .content(blogInfo.getTitle() + " " + blogInfo.getContent())
                    .updateTime(ZonedDateTime.now())
                    .build();
            esSearchService.addDocument(EsConst.BLOG_INDEX,String.valueOf(id),esBlog);
            log.info("id：{}，title：{}，addDocument success！",id,blogInfo.getTitle());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateElasticIndexById(Long id) {
        try {
            BlogInfoDto blogInfo = blogClientService.getBlogInfoById(id);
            EsBlog esBlog = EsBlog.builder()
                    .id(blogInfo.getId())
                    .content(blogInfo.getTitle() + " " + blogInfo.getContent())
                    .updateTime(ZonedDateTime.now())
                    .build();
            esSearchService.updateDocument(EsConst.BLOG_INDEX,String.valueOf(id),esBlog);
            log.info("id：{}，title：{}，updateDocument success！",id,blogInfo.getTitle());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteElasticIndexById(Long id) {
        try {
            esSearchService.deleteDocument(EsConst.BLOG_INDEX,String.valueOf(id));
            log.info("id：{}，deleteDocument success！",id);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
